package com.zero.java.base.stream;

import com.zero.java.base.model.City;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Lenovo
 * 
 *
 */
public class StreamReduceAPI2 {

	private static final String fileName = "cfg/citys.txt";

	public static void main(String[] args) throws Exception {

		Map<String, String> stateToCityName = readCity(fileName).collect(Collectors.groupingBy(City::getState,
				Collectors.reducing("", City::getName, (s, t) -> s.length() == 0 ? t : s + "," + t)));
		System.out.println(stateToCityName);

		// reduce求和实例
		List<Integer> numList = new ArrayList<Integer>();
		numList.add(10);
		numList.add(20);
		numList.add(30);
		numList.add(40);
		numList.add(50);

		// 第一种方式: reduce((total,num) -> total+num)
		Optional<Integer> result = numList.stream().reduce((x, y) -> x + y);
		System.out.println("第一种方式计算:" + result);

		// 第二种方式:
		Optional<Integer> result_02 = numList.stream().reduce(Integer::sum);
		System.out.println("第二种方式计算:" + result_02);
	}

	public static Stream<City> readCity(String fileName) throws Exception {

		Stream<String> cityLines = Files.lines(Paths.get(fileName));
		Stream<City> cityStream = cityLines.map(l -> l.split(","))
				.map(a -> new City(a[0], a[1], Integer.parseInt(a[2])));
		return cityStream;
	}
}
